package com.zto.sch.base.thread;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @program: sch-diy-parent
 * @description:三个运动员各自准备，等到三个都准备好过后再一
 * @author: sch
 * @create: 2021-01-09 23:11
 **/
public class ThreadDemo_CycleBarrier {
    public static void main(String[] args) {
        int count = 3;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
        final Random random = new Random();

        for (char threadName = 'A'; threadName < 'D'; threadName++) {
            String thN = String.valueOf(threadName);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    long prepareTime = random.nextInt(1000) + 1000;
                    System.out.println(thN + "-- is preparing for time: " + prepareTime);
                    try {
                        Thread.sleep(prepareTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    try {
                        System.out.println(thN + "--waiting for others");
                        cyclicBarrier.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    }

                    System.out.println(thN + "--start running ....");

                }
            }).start();
        }
    }
}
